package com.example.ribbontest.service;

import com.example.ribbontest.domain.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback")
    public String sayhello()
    {
        return restTemplate.getForEntity("http://SPRING-BOOT-TEST/hello",String.class).getBody();
    }

    public String helloFallback()
    {
        return "error";
    }

    @HystrixCommand(fallbackMethod = "helloUserFallback")
    public User helloUser()
    {
        System.out.println("begin call-----------");
        User u = restTemplate.getForObject("http://SPRING-BOOT-TEST/user",User.class);
        System.out.println("end call-----------");
        System.out.println(u.toString());
        return u;
    }

    public User helloUserFallback()
    {
        System.out.println("begin fallback-----------");
        return new User("error","error");
    }

    /**
     * 异步调用
     * @return
     */
    @HystrixCommand
    public Future<User> helloServiceAsyn()
    {
        return new AsyncResult<User>()
        {
            @Override
            public User invoke()
            {
                return restTemplate.getForObject("http://SPRING-BOOT-TEST/user",User.class);
            }

        };
    }
}
